package com.bluefox.uac.convertor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.bluefox.common.web.dto.AbstractConvertor;
import com.bluefox.uac.dto.UserDTO;
import com.bluefox.uac.model.User;
import com.bluefox.uac.service.UserService;
import lombok.NonNull;

import java.util.List;

/**
 * UserConvertor
 * @author SunFeng
 */
@Component
public class UserConvertor extends AbstractConvertor<User, UserDTO> {

    @Autowired
    private UserService userService;

    @Override
    public User toModel(@NonNull final UserDTO dto) {
        /**
         * //新增
         */
        if (dto.isNew()) {
            return constructModel(dto);
        } else {//更新
            return updateModel(dto);
        }
    }

    @Override
    public UserDTO toDTO(@NonNull final User model, final boolean forListView) {
        final UserDTO dto = new UserDTO();
        dto.setId(model.getId());
        dto.setUsername(model.getUsername());
        dto.setFullName(model.getFullName());
        dto.setPassword(model.getPassword());
        dto.setRoles(model.getRoles());
        dto.setEnable(model.getEnable());
        dto.setPhoneNumber(model.getPhoneNumber());
        dto.setBirthday(model.getBirthday());
        dto.setAddress(model.getAddress());
        dto.setType(model.getType());
        dto.setDescription(model.getDescription());
        dto.setAuthorities((List<GrantedAuthority>) model.getAuthorities());
        return dto;
    }

    // 构建新Model
    private User constructModel(final UserDTO dto) {
        User model = new User();
        model.setUsername(dto.getUsername());
        model.setFullName(dto.getFullName());
        model.setPassword(dto.getPassword());
        model.setRoles(dto.getRoles());
        model.setEnable(dto.getEnable());
        model.setPhoneNumber(dto.getPhoneNumber());
        model.setBirthday(dto.getBirthday());
        model.setAddress(dto.getAddress());
        model.setType(dto.getType());
        model.setDescription(dto.getDescription());
        model.setAuthorities((List<GrantedAuthority>) dto.getAuthorities());

        return model;
    }

    // 更新Model
    private User updateModel(final UserDTO dto) {
        User model = userService.get(dto.getId());
        model.setUsername(dto.getUsername());
        model.setFullName(dto.getFullName());
        model.setPassword(dto.getPassword());
        model.setRoles(dto.getRoles());
        model.setEnable(dto.getEnable());
        model.setPhoneNumber(dto.getPhoneNumber());
        model.setBirthday(dto.getBirthday());
        model.setAddress(dto.getAddress());
        model.setType(dto.getType());
        model.setDescription(dto.getDescription());
        model.setAuthorities((List<GrantedAuthority>) dto.getAuthorities());
        return model;
    }
}
